using System;
using Twitterizer;
using System.Timers;
using System.Collections.Generic;

namespace TwitterLib {
	public class Twitter
    {
        public delegate void TwitterMessageHandler(object feedback, TwitterEventArgs msg);
        public event TwitterMessageHandler TwitterMessageReceived;

        private static OAuthTokenResponse requestToken;
        private static OAuthTokens tokens;
        private Timer directMessageUpdateTimer;

        private DateTime lastCheck;
        private LinkedList<decimal> receivedDmIds;

        private String[] twitterAdministrators = new String[] { "duizendnegen", "GeertJohan" };

		public Twitter ()
        {
            requestToken = OAuthUtility.GetRequestToken("GwgO3s6pcXdyaEskVOZCAw", "aW1cNiD0P8ED1WJYqKiW89gjE2kf0BxNrmfN4JX4N8", "oob");
            Uri authorizationUrl = OAuthUtility.BuildAuthorizationUri(requestToken.Token);
            System.Diagnostics.Process.Start(authorizationUrl.AbsoluteUri);
            lastCheck = DateTime.Now;
            receivedDmIds = new LinkedList<decimal>();
		}

        public void OnTwitterMessageReceived(object feedback, TwitterEventArgs msg)
        {
            if (TwitterMessageReceived != null)
            {
                TwitterMessageReceived(feedback, msg);
            }
            else
            {
                throw new Exception("No listeners to twitter message.");
            }
        }

        public bool setPin(String pin)
        {
            OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken("GwgO3s6pcXdyaEskVOZCAw", "aW1cNiD0P8ED1WJYqKiW89gjE2kf0BxNrmfN4JX4N8", requestToken.Token, pin);

            tokens = new OAuthTokens();
            tokens.AccessToken = accessToken.Token;
            tokens.AccessTokenSecret = accessToken.TokenSecret;
            tokens.ConsumerKey = "GwgO3s6pcXdyaEskVOZCAw";
            tokens.ConsumerSecret = "aW1cNiD0P8ED1WJYqKiW89gjE2kf0BxNrmfN4JX4N8";

            TwitterResponse<TwitterDirectMessageCollection> dmResponse = TwitterDirectMessage.DirectMessages(tokens);
            String[] messages = new String[] { "Ground floor, ladies' clothes, sportswear, stationery", "First floor, kitchenware, furnishings, confectionary", "Second floor, children's toys, back to school, and many more", "Fourth floor, electronic, fake antiques, and lingerie" };
            TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, DateTime.Now.ToShortTimeString() + ": " + messages[new Random().Next(0, 3)]);
            if (tweetResponse.Result == RequestResult.Success)
            {
                directMessageUpdateTimer = new Timer(15000);
                directMessageUpdateTimer.Enabled = true;
                directMessageUpdateTimer.Elapsed += new ElapsedEventHandler(ReadDirectMessages);
                directMessageUpdateTimer.Start();

                return true;
            }
            else
            {
                return false;
            }
        }

        private void ReadDirectMessages(object source, ElapsedEventArgs e)
        {
            try
            {
                TwitterResponse<TwitterDirectMessageCollection> dmResponse = TwitterDirectMessage.DirectMessages(tokens);

                DateTime currentCheck = lastCheck;
                lastCheck = DateTime.Now;
                 
                foreach (TwitterDirectMessage dm in dmResponse.ResponseObject)
                {
                    if (!receivedDmIds.Contains(dm.Id) && dm.CreatedDate.CompareTo(currentCheck) >= 0) // if message was after the last check and hasn't been received yet
                    {
                        receivedDmIds.AddLast(dm.Id);

                        // check whether message is from allowed senders
                        bool isAdmin = false;

                        foreach (String administrator in twitterAdministrators)
                        {
                            if (administrator == dm.Sender.ScreenName)
                            {
                                isAdmin = true;
                                break;
                            }
                        }

                        if (isAdmin)
                        {
                            TwitterEventArgs args = new TwitterEventArgs(dm.Text);
                            OnTwitterMessageReceived(this, args);
                        }
                    }
                } 
            }
            catch(Exception ex){}
        }
        

		public void SendTweet(string message)
        {
            try
            {
                TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, message);
            }
            catch (Exception ex)
            {
                throw new Exception("Something went wrong: " + ex.Message);
            }
		}
	}
}

